package com.example.test.utils;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashMap;

public class Http {
    /**
     　　　* Post服务请求
     *
     * @param requestUrl 请求地址
     * @param requestbody 请求参数
     * @return
     */
    public static String sendPost(String requestUrl, String requestbody){

        try {
            //建立连接
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            //设置连接属性
            connection.setDoOutput(true); //使用URL连接进行输出
            connection.setDoInput(true); //使用URL连接进行输入
            connection.setUseCaches(false); //忽略缓存
            connection.setRequestMethod("POST"); //设置URL请求方法
            String requestString = requestbody;

            //设置请求属性
            byte[] requestStringBytes = requestString.getBytes(); //获取数据字节数据
            connection.setRequestProperty("Content-length", "" + requestStringBytes.length);
            connection.setRequestProperty("Content-Type", "application/octet-stream");
            connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            connection.setRequestProperty("Charset", "UTF-8");

            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);

            //建立输出流,并写入数据
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestStringBytes);
            outputStream.close();

            //获取响应状态
            int responseCode = connection.getResponseCode();

            if (HttpURLConnection.HTTP_OK == responseCode) { //连接成功
                //当正确响应时处理数据
                StringBuffer buffer = new StringBuffer();
                String readLine;
                BufferedReader responseReader;
                //处理响应流
                responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while ((readLine = responseReader.readLine()) != null) {
                    buffer.append(readLine).append("\n");
                }
                responseReader.close();
                Log.d("HttpPOST", buffer.toString());
                return buffer.toString();//成功
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "2";//失败

    }

    /**
     * Get服务请求
     *
     * @param requestUrl
     * @return
     */
    public static String sendGet(String requestUrl){
        try{
            //建立连接
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setDoOutput(false);
            connection.setDoInput(true);

            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);

            connection.connect();

            //获取响应状态
            int responseCode = connection.getResponseCode();

            if (HttpURLConnection.HTTP_OK == responseCode) { //连接成功
                //当正确响应时处理数据
                StringBuffer buffer = new StringBuffer();
                String readLine;
                BufferedReader responseReader;
                //处理响应流
                responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while ((readLine = responseReader.readLine()) != null) {
                    buffer.append(readLine).append("\n");
                }
                responseReader.close();
//                JSONObject result = new JSONObject(buffer.toString());
                Log.e("数据为：", buffer.toString());
                return buffer.toString();
            } else {
                Log.e("连接失败","liekai");
            }
        }catch (Exception e){
            Log.e("运行错误",e.toString());
            e.printStackTrace();
        }
        return null;
    }
    public static LinkedHashMap<String, Object> stringToJsonObject(String response) {
        try {
            Object json=new JSONTokener(response).nextValue();
            if(json instanceof JSONObject){
                JSONObject jso = new JSONObject(response);
                return JsonObjectToHashMap(jso);
            }else{
                JSONArray jsa=new JSONArray(response);
                return JsonArrayToHashMap(jsa);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }


    }
    public static LinkedHashMap<String, Object> JsonObjectToHashMap(JSONObject jso) {
        LinkedHashMap<String, Object> hashmap = new LinkedHashMap<>();
        try {
            for (Iterator<String> keyStr = jso.keys(); keyStr.hasNext(); ) {
                String key1 = keyStr.next().trim();
                if (jso.get(key1) instanceof JSONObject) {
                    JSONObject NextJSONObject=new JSONObject(jso.get(key1).toString());
                    hashmap.put(key1, JsonObjectToHashMap(NextJSONObject));
                }else if(jso.get(key1) instanceof JSONArray) {
                    JSONArray NextJSONArray =new JSONArray(jso.get(key1).toString());
                    hashmap.put(key1, JsonArrayToHashMap(NextJSONArray));
                }else {
                    hashmap.put(key1, jso.get(key1));
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return hashmap;
    }

    public static LinkedHashMap<String, Object> JsonArrayToHashMap(JSONArray jsa){
        LinkedHashMap<String, Object> hashMap = new LinkedHashMap<>();

        try {
            for (int i = 0; i < jsa.length(); i++) {
                if(jsa.get(i) instanceof JSONArray) {
                    JSONArray NextJSONArray=new JSONArray(jsa.get(i).toString());
                    hashMap.put(String.valueOf(i), JsonArrayToHashMap(NextJSONArray));
                }else if(jsa.get(i) instanceof JSONObject){
                    JSONObject NextJSONObject=new JSONObject(jsa.get(i).toString());
                    hashMap.put(String.valueOf(i),JsonObjectToHashMap(NextJSONObject));
                }
            }
        }catch (JSONException e){
            e.getStackTrace();
        }
        return hashMap;
    }



}
